package com.pmcc.core.config.security;

import com.pmcc.core.entity.security.Employee;
import com.pmcc.core.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Employee employee = employeeRepository.findByUsername(username);

        if (employee == null) {
            throw new UsernameNotFoundException(String.format("No employee found with username '%s'.", username));
        } else if(!employee.isEnabled()){
            throw new UsernameNotFoundException(String.format("employee blocked with username '%s'.", username));
        } else {
            return JwtUserFactory.create(employee);
        }
    }
}
